import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:identification_photo/config/constants.dart';
import 'package:identification_photo/utils/format_util.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';

/// 处理图片的工具类
class ImageUtil {
  ///创建一个图片的 ByteData
  ///[width] 图片宽度
  ///[height] 图片高度
  ///[bgColor] 背景颜色
  ///[imageFile] base64的图片路径(无头)
  static generateImageData(
      {required double width,
      required double height,
      bgColor = Colors.white,
      imageFile}) async {
    ///canvas的记录工具 用来保存canvas的
    final recorder = ui.PictureRecorder();

    ///canvas 绘图工具
    Canvas canvas = Canvas(recorder);

    ///画笔 颜色为传入颜色 状态是填充
    Paint paint = Paint();
    paint.color = bgColor;
    paint.style = PaintingStyle.fill;

    ///底下跟我画个背景
    canvas.drawRect(Rect.fromLTWH(0, 0, width, height), paint);

    ///顶上再画个人
    paint.color = Colors.black;
    paint.style = PaintingStyle.stroke;
    paint.strokeWidth = 10;
    ui.Image image = await base64ToImage(imageFile,
        width: width.toInt(), height: height.toInt());
    canvas.drawImage(image, Offset.zero, paint);
    // 转换成图片
    ///记录画的canvas
    Picture picture = recorder.endRecording();

    return await picture2ByteData(picture, width, height);
  }

  ///获取到的picture 转换成 ByteData
  ///[picture] canvas画然后记录的文件
  ///[width] 宽度
  ///[height] 高度
  static Future<ByteData?> picture2ByteData(
      ui.Picture picture, double width, double height) async {
    ui.Image img = await picture.toImage(width.toInt(), height.toInt());

    debugPrint('img的尺寸: $img');

    ByteData? byteData = await img.toByteData(format: ui.ImageByteFormat.png);

    return byteData;
  }

  ///base64 转成需要的Image文件 这个Image是UI 下面的Image和Image widget不同 !!!
  ///[asset] base64 无头字符串
  ///[width]宽度
  ///[height] 高度
  static Future<ui.Image> base64ToImage(String asset, {width, height}) async {
    Uint8List bytes = base64Decode(asset);
    ui.Codec codec = await ui.instantiateImageCodec(bytes,
        targetWidth: width, targetHeight: height);
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  ///选择一个图片
  ///[from] 是相机还是图库
  ///可选参数
  ///[maxWidth] 宽度,
  ///[maxHeight] 高度,
  ///[imageQuality] 质量
  static pickSinglePic(ImageFrom from,
      {double? maxWidth, double? maxHeight, int? imageQuality}) async {
    ImageSource source;
    switch (from) {
      case ImageFrom.camera:
        source = ImageSource.camera;
        break;
      case ImageFrom.gallery:
        source = ImageSource.gallery;
        break;
    }
    final pickerImages = await ImagePicker().pickImage(
      source: source,
      imageQuality: imageQuality,
      maxWidth: maxWidth,
      maxHeight: maxHeight,
    );
    return pickerImages;
  }

  ///裁切图片
  ///[image] 图片路径或文件
  ///[width] 宽度
  ///[height] 高度
  ///[aspectRatio] 比例
  ///[androidUiSettings]UI 参数
  ///[iOSUiSettings] ios的ui 参数
  static cropImage(
      {required image,
      required width,
      required height,
      aspectRatio,
      androidUiSettings,
      iOSUiSettings}) async {
    String imagePth = "";
    if (image is String) {
      imagePth = image;
    } else if (image is File) {
      imagePth = image.path;
    } else {
      throw ("文件路径错误");
    }
    final croppedFile = await ImageCropper().cropImage(
      sourcePath: imagePth,
      maxWidth: FormatUtil.num2int(width),
      maxHeight: FormatUtil.num2int(height),
      aspectRatio: aspectRatio ??
          CropAspectRatio(
              ratioX: FormatUtil.num2double(width),
              ratioY: FormatUtil.num2double(height)),
      uiSettings: [
        androidUiSettings ??
            AndroidUiSettings(
                toolbarTitle:
                    '图片裁切(${FormatUtil.num2int(width)}*${FormatUtil.num2int(height)})',
                toolbarColor: Colors.blue,
                toolbarWidgetColor: Colors.white,
                initAspectRatio: CropAspectRatioPreset.original,
                hideBottomControls: false,
                lockAspectRatio: true),
        iOSUiSettings ??
            IOSUiSettings(
              title: 'Cropper',
            ),
      ],
    );
    return croppedFile;
  }

}
